from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.utils.commons import login_required
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu


# 收藏新闻
@profile_blu.route('/collection')
@login_required
def user_collection_news():
    """
    用户收藏新闻信息:
    """
    user = g.user
    # 1. 接收参数并进行参数校验
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:

        pagination = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = pagination.items
        total_page = pagination.pages
        current_page = pagination.page

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询收藏新闻失败')
    return render_template('news/user_collection.html',
                           news_li=news_li,
                           total_page=total_page,
                           current_page=current_page)


# 修改用户密码
@profile_blu.route('/password', methods=['GET', 'POST'])
@login_required
def user_password():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html', user=user)
    else:
        req_dict = request.json
        if not req_dict:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        old_password = req_dict.get('old_password')
        new_password = req_dict.get('new_password')

        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

        # 原密码校验
        if not user.check_passowrd(old_password):
            return jsonify(errno=RET.PWDERR, errmsg='原密码错误')

        # 修改参数
        user.password = new_password
        # 提交到数据库中
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='修改密码失败')

        return jsonify(errno=RET.OK, errmsg='修改密码成功')


# 用户头像信息
@profile_blu.route('/avatar', methods=['GET', 'POST'])
@login_required
def user_avatar():
    user = g.user
    if request.method == 'GET':
        return render_template("news/user_pic_info.html", user=user)
    else:
        # 保存用户上传头像
        file = request.files.get('avatar')
        if not file:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少图片')
        # 图片文件上传到七牛云
        try:
            key = storage(file.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='上传用户头像失败')
        # 设置用户表中用户头像的地址
        user.avatar_url = key
        # 上传到数据库中
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='保存用户头像记录失败')
        avatar_url = constants.QINIU_DOMIN_PREFIX + key
        return jsonify(errno=RET.OK, errmsg='头像上传成功', avatar_url=avatar_url)


# 修改用户资料
@profile_blu.route('/basic', methods=['GET', 'POST'])
@login_required
def user_basic():
    user = g.user
    if request.method == 'GET':

        return render_template('news/user_base_info.html', user=user)
    else:
        # 获取参数校验用户信息完整性
        req_dict = request.json
        if not req_dict:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        signature = req_dict.get('signature')
        nick_name = req_dict.get('nick_name')
        gender = req_dict.get('gender')
        if not all([signature, nick_name, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
        # 判断性别只有2个选项
        if gender not in ('MAN', 'WOMAN'):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        # 修改参数
        user.signature = signature
        user.nick_name = nick_name
        user.gender = gender
        # 提交到数据库中
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='保存信息失败')
        # 设置session中的nickname
        session['nick_name'] = nick_name

        return jsonify(errno=RET.OK, errmsg='保存信息成功')


@profile_blu.route('')
@login_required
def get_user_profile():
    """用户个人中心"""
    user = g.user
    return render_template('news/user.html', user=user)
